#include <stdlib.h>
#include <string.h>
#include "list.h"

/* append a new element at the end of the list */
int ListAdd (List *list,void *data,int size)
{
   List l;

   /* generate new list node */
   l = (List)malloc(sizeof(struct _List));
   if (l) {
      l->next = 0;
      l->prev = 0;
      l->data = malloc(size);
      if (l->data)
         memcpy(l->data,data,size);
      else {
         free (l);
         l = NULL;
      }
   }

   /* insert new node at end of list */
   if (l) {
      if (*list == NULL)
         *list = l;
      else {
         List last;
         last = *list;
         while (last->next)
            last = last->next;
         last->next = l;
         l->prev = last;
      }
   }

   return (l != NULL);
}

/* go to the next list element; return 1 if done, 0 else */
int ListNext (List *list)
{
   if (list && (*list)->next) {
      *list = (*list)->next;
      return 1;
   }
   return 0;
} 
  
/* go to the previous list element; return 1 if done, 0 else */
int ListPrev (List *list)
{
   if (list && (*list)->prev) {
      *list = (*list)->prev;
      return 1;
   }
   return 0;
} 

void * ListGetData (List list)
{
   if (list && list->data)
      return list->data;
   return NULL;
}
 
/* free all elements in the list */
void ListFree (List list)
{
   List next;

   while (list) {
      next = list->next;
      free(list->data);
      free(list);
      list = next;
   }
}
